<template>
  <div class="agv-list-wrapper project">
    <!-- 查询条件 -->
    <div class="project-search">
      <el-form class="search-form" ref="formRef" label-suffix=" :" :model="productModelParams" @submit.prevent>
        <div class="search-list">
          <el-form-item label="车辆注册：">
            <el-radio-group v-model="productModelParams.isRegister" @change="getTableList">
              <el-radio-button label="已注册" :value="1" />
              <el-radio-button label="未注册" :value="0" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="车型">
            <el-select v-model="productModelParams.productCategoryId" placeholder="请选择" clearable filterable>
              <el-option v-for="item in agvTypeList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="订单">
            <el-select v-model="productModelParams.projectId" placeholder="请选择" clearable filterable>
              <el-option v-for="item in projectList" :key="item.id" :label="item.nameClone" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="车架号/订单编号">
            <el-input v-model="productModelParams.searchKey" placeholder="请输入"></el-input>
          </el-form-item>
        </div>
        <div class="operation">
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="getTableList" native-type="submit"> 搜索 </el-button>
            <el-button :icon="Refresh" @click="reset"> 重置 </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <!-- 车辆列表 -->
    <div class="project-content">
      <div class="content-top">
        <el-button v-auth="'add'" type="primary" :icon="Plus" @click="jumpDetail(1)"> 新增产品 </el-button>
        <el-button :icon="Refresh" circle />
      </div>
      <el-scrollbar>
        <div class="cot-list-wrap">
          <ul ref="listWrapRef" class="cot-list" :style="`--gap: ${gap}px ${gap}px`">
            <li class="list-item" v-for="(item, index) in productModel" :key="index" @click="jumpDetail(2, item.id)">
              <div class="img">
                <img :src="urlResource + item.picture" alt="" />
              </div>
              <div class="text-container">
                <div class="title">{{ setInfo(item.productCategoryName) }}</div>
                <div @click.stop><span>车架号</span>{{ setInfo(item.code) }}</div>
                <div @click.stop><span>仪表ID</span>{{ setInfo(item.deviceId) }}</div>
                <div class="version">
                  <span>软件版本</span>{{ setInfo(item.deviceSwVersion) }}
                  <div
                    class="version-progress"
                    :class="{ block: item.upgrading }"
                    v-auth="'upgrade'"
                    v-if="item.state && getDictItem('vehicleStatus', item.state) == 'online'"
                  >
                    <el-progress v-if="item.upgrading" :stroke-width="5" :percentage="50" />
                    <Upload
                      v-else
                      @click.stop
                      :multiple="false"
                      :show-file-list="false"
                      :limit="1"
                      :api="upgradeFmsOta"
                      :params="{ deviceId: item.deviceId }"
                      height="20px"
                      @change="upRefresh"
                    >
                      <el-button v-auth="'upgrade'" type="primary" link> 更新固件 </el-button>
                    </Upload>
                  </div>
                </div>
                <div class="locker">
                  <span>锁车状态</span>
                  <div class="locker-status" :class="{ isLock: item.lockState }">{{ changeStatus(item.lockState) }}</div>
                  <div
                    class="locker-progress"
                    v-auth="'lockState'"
                    v-if="item.state && getDictItem('vehicleStatus', item.state) == 'online'"
                  >
                    <div class="button" @click.stop="changeStatusFn(item)">{{ item.lockState ? "解锁车辆" : "锁定车辆" }}</div>
                  </div>
                </div>
                <div class="sle" style="width: 200px"><span>项目名称</span>{{ item.projectName }}</div>
              </div>
              <div @click.stop class="position">
                <el-dropdown trigger="click" v-auth="{ not: ['update', 'delete'] }">
                  <span class="el-dropdown-link">
                    <div class="tit-right">...</div>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <!-- <el-dropdown-item @click="jumpDetail(2, item.id)" v-auth="'update'"> 编辑 </el-dropdown-item> -->
                      <el-dropdown-item @click="handleDelete(item)" v-auth="'delete'">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div v-if="item.state" class="status" :class="agvStatus[getDictItem('vehicleStatus', item.state)]">
                {{ getDictItem("vehicleStatus", item.state) }}
              </div>
            </li>
          </ul>
          <el-empty :image-size="200" v-if="!productModel.length" description="暂无项目" />
        </div>
      </el-scrollbar>
      <div class="pagination">
        <el-pagination
          :background="true"
          :current-page="pageable.pageNum"
          :page-size="pageable.pageSize"
          :page-sizes="[10]"
          :total="pageable.total"
          layout="total, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>
    <!-- <AgvDrawer v-if="visible" v-model:visible="visible" :revise-params="reviseParams" @refresh="getTableList" /> -->
    <!-- <Detail v-if="drawerVisibleDetail" v-model:drawerVisibleDetail="drawerVisibleDetail" :id="itemId" v-auth="'detail'"></Detail> -->
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, onUnmounted, onMounted, onBeforeUnmount, inject } from "vue"; // onMounted
import { Search, Plus, Refresh } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { getProductPage, delProductDelete, getFmsOtaProgress, upgradeFmsOta, getFmsProductLock } from "@/api/modules/agv"; //  addProductAdd, updateProductUpdate,
import Upload from "@/components/Upload/upload.vue";
import { getProductModelList } from "@/api/modules/carType";
import { getProjectListCodeAll } from "@/api/modules/project";

import { ElMessage } from "element-plus";
// import AgvDrawer from "./AgvDrawer.vue";
// import Detail from "./Detail.vue";
import { useDict } from "@/hooks/useDict";
import { useUtils } from "./hooks/useUtils";
import { customSetInterval } from "@/utils";
import { useHandleData } from "@/hooks/useHandleData";
// interface reviseParam {
//   id: string | undefined;
//   uiType: number;
//   title: string;
// }

/**
 * 变量
 */
const router = useRouter();
const agvStatus = ref({
  online: "#74D98C",
  offline: "#DDDFE6",
  broken: "#F56C6C"
});
const { getDictItem } = useDict(["vehicleStatus"]);
const { setInfo } = useUtils();
const urlResource = inject("urlResource");
// const visible = ref(false);
// const reviseParams = ref<reviseParam>({
//   id: "",
//   uiType: 1, // 1: 新增 2: 修改
//   title: ""
// });
const pageable = ref({
  pageNum: 1,
  pageSize: 20,
  total: 0
});
let gap = ref(15);
const listWrapRef = ref();
// 查询条件
let productModelParams = ref<any>({
  isRegister: 1,
  productCategoryId: "",
  projectId: "",
  searchKey: ""
});
const timeList = ref([]);
/**
 * 方法
 */
const reset = () => {
  productModelParams.value.isRegister = 1;
  productModelParams.value.productCategoryId = "";
  productModelParams.value.projectId = "";
  productModelParams.value.searchKey = "";
  getTableList();
};
// 切换车锁状态
const changeStatusFn = async (row: any) => {
  // console.log(auditContent, row);
  await useHandleData(
    getFmsProductLock,
    { deviceId: row.deviceId, lockState: +!row.lockState },
    `切换【${row.productCategoryName}】车辆锁状态`
  );
  getTableList();
};
// 获取升级进度
const getFmsOtaProgressFn = async (deviceId: string) => {
  const { data } = await getFmsOtaProgress({ deviceId });
  if (data)
    productModel.value.forEach((item: any) => {
      if (item.deviceId === deviceId) {
        item.bfb = parseInt((data.sequence / data.total) * 100);
        if (item.bfb === 100) {
          getTableList();
        }
      }
    });
};
// 定时轮询状态
const interVal = deviceId => {
  const timer = customSetInterval(() => {
    getFmsOtaProgressFn(deviceId);
  }, 5000);
  timeList.value.push(timer);
};
const upRefresh = () => {
  getTableList();
};

const jumpDetail = (type: number, id?: string) => {
  router.push({
    path: "/agv/detail",
    query: {
      type: type,
      id: id
    }
  });
  // itemId.value = id;
};
// const reviseHandler = (type: number, id?: string) => {
//   // reviseParams.value.uiType = type;
//   // reviseParams.value.id = id;
//   // reviseParams.value.title = type === 1 ? "新增" : "编辑";

// };

// const objResizeObserver = new ResizeObserver(function (entries) {
//   const entry = entries[0];
//   const cr = entry.contentRect;
//   const num = Math.floor(cr.width / 388);
//   gap.value = (cr.width - num * 388) / (num - 1);
// });

// 转换锁车状态
const changeStatus = (status: number) => {
  switch (status) {
    case 0:
      return "正常";
    case 1:
      return "已上锁";
    default:
      return "--";
  }
};

//  获取所有车型
const agvTypeList = ref<any>([]);
const getCarType = async () => {
  const { data } = await getProductModelList();
  agvTypeList.value = data || [];
};
// 获取所有项目
const projectList: any = ref([]);
const getProject = async () => {
  const { data } = await getProjectListCodeAll();
  projectList.value =
    (data &&
      data.map((item: any) => {
        item.nameClone = item.code + "-" + item.name;
        return item;
      })) ||
    [];
};

const handleDelete = async (item: any) => {
  await delProductDelete({ id: item.id });
  ElMessage.success({ message: `删除车辆成功！` });
  getTableList();
};

const productModel: any = ref([]);
const getTableList = async () => {
  const { data } = await getProductPage({
    ...productModelParams.value,
    currentPage: pageable.value.pageNum,
    pageSize: pageable.value.pageSize
  });
  productModel.value = data.records || [];
  pageable.value.total = Number(data.total);
  // 轮询升级
  productModel.value.forEach((item: any) => {
    if (item.upgrading) {
      interVal(item.deviceId);
    }
  });
};

//分页
const handleSizeChange = () => {};
const handleCurrentChange = (val: any) => {
  pageable.value.pageNum = val;
  getTableList();
};
// 释放定时器
const unTimer = () => {
  if (timeList.value.length) {
    timeList.value.forEach(item => {
      item.cancel();
    });
    timeList.value = [];
  }
};
onBeforeUnmount(() => {
  // objResizeObserver.unobserve(listWrapRef.value);
});
onMounted(() => {
  // 观察文本域元素
  // objResizeObserver.observe(listWrapRef.value);
  getCarType();
  getProject();
  getTableList();
});
onUnmounted(() => {
  unTimer();
});
</script>
<style scoped lang="scss">
.agv-list-wrapper {
  display: flex;
  flex-flow: column nowrap;
  height: 100%;
  .project-search {
    box-sizing: border-box;
    display: flex;
    flex: 0 0 72px;
    align-items: center;
    justify-content: space-between;
    padding: 0 30px;
    margin-bottom: 10px;
    background: #ffffff;
    .search-form {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      .operation {
        .el-form-item--default {
          margin-bottom: 0;
        }
      }
    }
    .search-list {
      display: flex;
      gap: 56px;
      align-items: center;
      .el-form-item--default {
        flex: 0 0 240px;
        margin-bottom: 0;
      }
    }
    :deep(.el-input__inner) {
      min-width: 160px !important;
    }
  }
  .project-content {
    box-sizing: border-box;
    display: flex;
    flex: 1;
    flex-flow: column nowrap;
    justify-content: space-between;
    height: 0;
    background: #ffffff;
    .pagination {
      display: flex;
      justify-content: flex-end;
      padding: 20px;
    }
    .content-top {
      display: flex;
      flex: 0 0 72px;
      align-items: center;
      justify-content: space-between;
      padding: 0 30px;
    }
    .cot-list-wrap {
      flex: 1;
      height: 0;
      padding: 0 30px;
    }
    .cot-list {
      box-sizing: border-box;
      display: grid;
      grid-template-columns: repeat(auto-fill, 388px);
      gap: var(--gap);
      padding: 10px 2px;
      li {
        position: relative;
        box-sizing: border-box;
        width: 388px;
        cursor: pointer;
        background: #ffffff;
        border: 1px solid #f5f5f5;
        &:hover {
          outline: 2px solid var(--el-color-primary);
          .text-container {
            .locker {
              &-progress {
                display: block;
                font-size: 12px;
                color: #5378f6;
              }
            }
            .version {
              &-progress {
                display: block;
                font-size: 12px;
                color: #5378f6;
              }
            }
          }
        }
      }
      .list-item {
        position: relative;
        box-sizing: border-box;
        display: flex;
        gap: 10px;
        padding: 20px;
        font-size: 12px;
        transition: background-color 0.3s;
        .img {
          flex: 0 0 150px;
          width: 150px;
          height: 150px;
          background: #fafafc;
          img {
            width: 100%;
            height: 100%;
            object-fit: contain;
          }
        }
        .text-container {
          display: flex;
          flex: 1;
          flex-direction: column;
          gap: 8px;
          .title {
            margin-bottom: 2px;
            font-size: 16px;
            color: #333333;
          }
          span {
            margin-right: 10px;
            color: #999999;
          }
          .locker {
            position: relative;
            display: flex;
            .locker-status {
              color: #74d98c;
            }
            .isLock {
              color: red;
            }
            &-progress {
              position: absolute;
              top: 0;
              right: 0;
              display: none;
            }
          }
          .version {
            position: relative;
            &-progress {
              position: absolute;
              top: 0;
              right: 0;
              display: none;
              width: 72%;
              text-align: right;
              :deep(.upload-box-s) {
                display: inline-block;
                font-size: 12px;
                .el-button {
                  padding: 0;
                  span {
                    font-size: 12px;
                  }
                }
              }
            }
          }
        }
        .status {
          position: absolute;
          top: 20px;
          left: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50px;
          height: 20px;
          font-weight: 600;
          color: white;
          background-color: #74d98c;
        }
      }
      .position {
        position: absolute;
        top: 10px;
        right: 10px;
        .tit-right {
          display: flex;
          align-self: flex-start;
          margin-top: 10px;
          margin-right: 0;
          font-weight: bold;
          line-height: 0;
          color: #333333;
          letter-spacing: 3px;
          cursor: pointer;
          transform: rotate(-90deg);
        }
      }
    }
  }
  .block {
    display: block !important;
  }
}
</style>
